package org.m2acsi.boundary;

import com.mongodb.ObjectId;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.m2acsi.entities.Document;

@ManagedBean
public class FileManager {

    GridFS gfsPhoto;
//    @Inject
//    MongoConnection mgConnection;

    public FileManager() {
        this.gfsPhoto = new GridFS(MongoConnection.getMongoConnection(), "Files");
//        this.gfsPhoto = new GridFS(mgConnection.getDb(), "Files");
    }

    public FileManager(String gridFSName) {
        this.gfsPhoto = new GridFS(MongoConnection.getMongoConnection(), gridFSName);
//        this.gfsPhoto = new GridFS(mgConnection.getDb(), gridFSName);
    }

    public Document uploadFile(InputStream inputStream, String name) throws IOException {
        GridFSInputFile gfsFile = gfsPhoto.createFile(inputStream);
        gfsFile.setFilename(name);
        gfsFile.save();
        return new Document(gfsFile.getFilename(), gfsFile.getId().toString());
    }

    public void getFile(String mongoID) {
        //Requete precompile : http://docs.mongodb.org/ecosystem/drivers/java-types/
        //Get file
        ObjectId oID = new ObjectId(mongoID);
        GridFSDBFile imageForOutput = gfsPhoto.findOne(oID);

        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
//        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        ec.responseReset();
//        TODO Add the content type
        ec.setResponseContentType(imageForOutput.getContentType());
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + imageForOutput.getFilename() + "\"");
        try {
            OutputStream output = ec.getResponseOutputStream();
            imageForOutput.writeTo(output);
            output.close();
        } catch (IOException ex) {
            Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        fc.responseComplete();
    }
}
